import shopFn from "../../api/shopping";

export default {
  namespaced: true,
  state: {
    car: [],
    total: 0,
    checkOut: null,
  },
  mutations: {
    SET_CAR(state, item) {
      state.car.push({
        id: item.id,
        num: 1,
      });
    },
    ADD_CAR(state, item) {
      state.car.map((v) => {
        if (v.id == item.id) {
          v.num++;
        }
      });
    },
    SET_CEHCK(state, text) {
      state.checkOut = text;
    },
    SET_BBB(state, item) {
      state.car = item;
    },
  },
  actions: {
    addCar({ commit, state, dispatch }, item) {
      state.checkOut = null;
      let hasId = state.car.find((v) => v.id == item.id);
      if (hasId) {
        commit("ADD_CAR", item);
      } else {
        commit("SET_CAR", item);
      }
      dispatch("shop/reduceInventory", item, { root: true });
    },
    buy({ commit, state }) {
      shopFn.buyProducts(
        {},
        () => {
          commit("SET_CEHCK", "成功");
          commit("SET_BBB", []);
        },
        () => {
          commit("SET_CEHCK", "失败");
          commit("SET_BBB", state.car);
        }
      );
    },
  },
  getters: {
    NewCar(state, getters, rootState) {
      return state.car.map((item) => {
        let findCar = rootState.shop.products.find((v) => v.id == item.id);
        return {
          title: findCar.title,
          price: findCar.price,
          num: item.num,
        };
      });
    },
    total(state, getters) {
      return (state.total = getters.NewCar.reduce((t, v) => {
        return t + v.price * v.num;
      }, 0));
    },
  },
};
